﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using QRCoder;
using System.Drawing;
using System.Configuration;
using System.Web.UI;
using Infragistics.WebUI.UltraWebNavigator;

public partial class ContainerPlatoonPopupForm : ShopfloorPage, INormalReport
{
    const string QueryWhere = "ContainerPlatoonPopupForm";
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESContainerPrintBusiness bll = new uMESContainerPrintBusiness();
    uMESContainerPlatoonBusiness plat = new uMESContainerPlatoonBusiness();
    uMESDispatchBusiness dispatch = new uMESDispatchBusiness();
    uMESProductTreeViewBusiness productTreeBal = new uMESProductTreeViewBusiness();
    uMESContainerBusiness containerBal = new uMESContainerBusiness();
    int m_PageSize = 15;
    string businessName = "批次管理", parentName = "Container";
    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：生产批次预派工";
        master.strTitle = "";//生产批次预派工
        master.ChangeFrame(true);
        NormalReportControl normalCntrl = new NormalReportControl();
        normalCntrl.LtnFirst = lbtnFirst;
        normalCntrl.LtnLast = lbtnLast;
        normalCntrl.LtnNext = lbtnNext;
        normalCntrl.LtnPrev = lbtnPrev;
        normalCntrl.BtnReset = btnReSet;
        normalCntrl.BtnGo = btnGo;
        normalCntrl.BtnSearch = btnSearch;
        normalCntrl.LabPages = lLabel1;
        normalCntrl.TxtPage = txtPage;
        normalCntrl.TxtTotalPage = txtTotalPage;
        normalCntrl.TxtCurrentPage = txtCurrentPage;
        normalCntrl.NormalOperation = this;
        normalCntrl.QueryWhere = QueryWhere;

        WebPanel = WebAsyncRefreshPanel1;

        getProductInfo.DDlProductDataChanged += new GetProductInfo_ascx.DDlProductDataChangedEventHandler(() => { ProductTreeSearch(); });
        if (!IsPostBack)
        {
            //ClearMessage_PageLoad();
            getProductInfo.GetProductControlDiv.Style["width"] = "190px"; getProductInfo.GetSearchBtn.Visible = false;
        }
    }

    #region 重置
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        ResetData();
    }
    
    #endregion

    #region 数据查询
    public Dictionary<string, string> GetQuery()
    {
        string strProcessNo = txtProcessNo.Text.Trim();
        string strContainerName = txtContainerName.Text.Trim();
        string strProductName = txtProductName.Text.Trim();
        string strStartDate = txtStartDate.Value.Trim();
        string strEndDate = txtEndDate.Value.Trim();

        Dictionary<string, string> result = new Dictionary<string, string>();
        result.Add("ProcessNo", strProcessNo);
        result.Add("ContainerName", strContainerName);
        result.Add("ProductName", strProductName);
        result.Add("StartDate", strStartDate);
        result.Add("EndDate", strEndDate);
        result.Add("IsAPS", "0");
        result["State"] = "0,20";//add:Wangjh 1126 预派工情况下增加状态筛选

        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        string strEmployeeID = userInfo["EmployeeID"];

        result.Add("MfgManagerid", strEmployeeID);

        Session[QueryWhere] = result;

        return result;
    }

    public void QueryData(Dictionary<string, string> query)
    {
        //ClearMessage();

        try
        {
            EnabledPage();
            uMESPagingDataDTO result = bll.GetSourceData(query, Convert.ToInt32(this.txtCurrentPage.Text), m_PageSize);
            this.ItemGrid.DataSource = result.DBTable;
            this.ItemGrid.DataBind();
            this.txtTotalPage.Text = result.PageCount;
            if (result.RowCount == "0")
            {
                this.txtCurrentPage.Text = "0";
            }
            lLabel1.Text = string.Format("第 {0} 页  共 {1} 页", this.txtCurrentPage.Text, this.txtTotalPage.Text);
            this.txtPage.Text = this.txtCurrentPage.Text;
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    public void ResetQuery()
    {
        Session[QueryWhere] = "";
        txtScan.Text = string.Empty;
        txtProcessNo.Text = string.Empty;
        txtContainerName.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtStartDate.Value = string.Empty;
        txtEndDate.Value = string.Empty;
        ItemGrid.Rows.Clear();

        this.txtTotalPage.Text = "";
        this.txtCurrentPage.Text = "";
        this.txtPage.Text = "";
        lLabel1.Text = "第  页  共  页";
    }

    void ResetData()
    {
        //ShowStatusMessage("", true);
        txtScan.Text = string.Empty;
        txtProcessNo.Text = string.Empty;
        txtContainerName.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtStartDate.Value = string.Empty;
        txtEndDate.Value = string.Empty;
        ItemGrid.Rows.Clear();

        this.txtTotalPage.Text = "";
        this.txtCurrentPage.Text = "";
        this.txtPage.Text = "";
        lLabel1.Text = "第  页  共  页";
        txtSrTreeProcessNo.Text = "";
        txtSrTreeProduct.Text = "";

    }
    #endregion

    #region 分页按钮
    protected void lbtnFirst_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnPrev_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnNext_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnLast_Click(object sender, EventArgs e)
    {

    }
    protected void btnGo_Click(object sender, EventArgs e)
    {

    }
    #endregion

    protected void txtScan_TextChanged(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            string strScan = txtScan.Text.Trim();
            txtScan.Text = "";

            if (strScan != string.Empty)
            {
                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("ScanContainerName", strScan);

                Session[QueryWhere] = para;

                txtCurrentPage.Text = "1";
                QueryData(para);
            }
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    #region 预派工按钮
    protected void btnAPS_Click(object sender, EventArgs e)
    {
        //ClearMessage();

        try
        {
            int intCount = 0;
            List<string> listWorkflowID = new List<string>();Dictionary<string,string> paraContainers=new Dictionary<string, string>();

            TemplatedColumn temCell = (TemplatedColumn)ItemGrid.Columns.FromKey("ckSelect");

            for (int i = 0; i < temCell.CellItems.Count; i++)
            {
                Infragistics.WebUI.UltraWebGrid.CellItem cellItem = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell.CellItems[i];
                CheckBox ckSelect = (CheckBox)cellItem.FindControl("ckSelect");

                if (ckSelect.Checked == true)
                {
                    string strWorkflowID = ItemGrid.Rows[i].Cells.FromKey("WorkflowID").Value.ToString();
                    listWorkflowID.Add(strWorkflowID);
                    intCount++;
                }
            }

            if (intCount == 0)
            {
                ShowStatusMessage("请选择要预派工的批次", false);
                return;
            }

            //获取工序列表
            DataTable DT = common.GetSpecListByWorkflowID(listWorkflowID);

            //每天工作时间段
            DataTable dtDaySJD = plat.GetDaySJD_Config();
            //是否包含周末
            Boolean IsIncludeSS = plat.IsIncludeSS();

            for (int i = 0; i < temCell.CellItems.Count; i++)
            {
                Infragistics.WebUI.UltraWebGrid.CellItem cellItem = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell.CellItems[i];
                CheckBox ckSelect = (CheckBox)cellItem.FindControl("ckSelect");

                if (ckSelect.Checked == true)
                {
                    string IsAPS = ItemGrid.Rows[i].Cells.FromKey("IsAPS").Value.ToString();

                    if (IsAPS == "0") //未预派工的批次进行预派工，已派工的批次因为未进行计划延迟所以不再重新计算
                    {
                        string strPlannedStartDate = string.Empty;
                        if (ItemGrid.Rows[i].Cells.FromKey("PlannedStartDate").Value != null)
                        {
                            strPlannedStartDate = ItemGrid.Rows[i].Cells.FromKey("PlannedStartDate").Value.ToString();
                        }
                        else
                        {
                            strPlannedStartDate = DateTime.Now.ToString("yyyy-MM-dd");
                        }

                        DateTime startTime = Convert.ToDateTime(strPlannedStartDate);
                        paraContainers.Add(ItemGrid.Rows[i].Cells.FromKey("ContainerID").Text, ItemGrid.Rows[i].Cells.FromKey("ContainerName").Text);//记录需要处理的批次
                        APS(DT, i, startTime);
                    }
                }
            }

            //Dictionary<string, string> para = (Dictionary<string, string>)Session[QueryWhere];
            //QueryData(para);

            #region 存储日志
            ContainerExcuteLog(paraContainers);
            #endregion

            ShowStatusMessage("预派工完成", true);
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>parent.window.returnValue='true';window.close();</script>");
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }
    #endregion

    #region 预派工
    /// <summary>
    /// 给指定的批次进行预派工操作
    /// </summary>
    /// <param name="dtSpecList">工序列表</param>
    /// <param name="intRowIndex">批次行号</param>
    /// <param name="startDate">计划开始日期</param>
    protected void APS(DataTable dtSpecList, int intRowIndex, DateTime startDate)
    {
        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        string strDispatchEmployeeID = userInfo["EmployeeID"];

        //string strPlannedStartDate = string.Empty;
        //if (ItemGrid.Rows[intRowIndex].Cells.FromKey("PlannedStartDate").Value != null)
        //{
        //    strPlannedStartDate = ItemGrid.Rows[intRowIndex].Cells.FromKey("PlannedStartDate").Value.ToString();
        //}
        //else
        //{
        //    strPlannedStartDate = DateTime.Now.ToString("yyyy-MM-dd");
        //}

        string strContainerID = ItemGrid.Rows[intRowIndex].Cells.FromKey("ContainerID").Value.ToString();
        string strWorkflowID = ItemGrid.Rows[intRowIndex].Cells.FromKey("WorkflowID").Value.ToString();
        string strQty = ItemGrid.Rows[intRowIndex].Cells.FromKey("Qty").Value.ToString();

        //工序列表
        DataRow[] rowsSpecList = dtSpecList.Select(string.Format("WorkflowID = '{0}'", strWorkflowID), "Sequence ASC");

        //DateTime startTime = Convert.ToDateTime(strPlannedStartDate);
        DateTime startTime = startDate;

        for (int j = 0; j < rowsSpecList.Length; j++)
        {
            string strDispatchInfoName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string strSpecName = rowsSpecList[j]["specname"].ToString();
            string strSpecID = rowsSpecList[j]["SpecID"].ToString();
            string strTeamID = rowsSpecList[j]["TeamID"].ToString();
            //齐套工序取下一工序的班组信息
            if (strSpecName.Contains("齐套"))
            {
                if (j < rowsSpecList.Length - 1)
                {
                    strTeamID = rowsSpecList[j + 1]["TeamID"].ToString();
                }
            }
            string strResourceGroupID = rowsSpecList[j]["ResourceGroupID"].ToString();
            string strSequence = rowsSpecList[j]["Sequence"].ToString();
            string strWorkflowStepID = rowsSpecList[j]["WorkflowStepID"].ToString();

            //单位工时
            string strUnitWorkTime = rowsSpecList[j]["UnitWorkTime"].ToString();
            //工时系数
            Double dblXS = Convert.ToDouble(rowsSpecList[j]["WorkTimeXS"].ToString());
            //总工时
            Double dblGS = Convert.ToDouble(strQty) * Convert.ToDouble(strUnitWorkTime) * 60 * dblXS;

            int intGS = Convert.ToInt32(dblGS);

            PlannedTimes pt = plat.GetPlannedTimes(startTime, intGS);
            startTime = pt.StartTime;
            DateTime endTime = pt.EndTime;

            Dictionary<string, string> para = new Dictionary<string, string>();
            para.Add("DispatchInfoName", strDispatchInfoName);
            para.Add("ContainerID", strContainerID);
            para.Add("SpecID", strSpecID);
            para.Add("DispatchEmployeeID", strDispatchEmployeeID);
            para.Add("DispatchDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            para.Add("DispatchType", "0");
            para.Add("DispatchToType", "0");
            para.Add("ContainerPhaseID", "");
            para.Add("PlannedStartDate", startTime.ToString("yyyy-MM-dd HH:mm:ss")); //需要通过计算获得
            para.Add("PlannedCompletionDate", endTime.ToString("yyyy-MM-dd HH:mm:ss")); //需要通过计算获得
            para.Add("Qty", strQty);
            para.Add("UOMID", "");
            para.Add("ResourceID", "");
            para.Add("Status", "0"); //已派工
            para.Add("ParentID", "");
            para.Add("WorkflowID", strWorkflowID);
            para.Add("TeamID", strTeamID);//需要从工序信息中读取
            para.Add("TotalGS", dblGS.ToString());
            para.Add("SpecSequence", strSequence);
            para.Add("ResourceGroupID", strResourceGroupID);
            para.Add("IsAPS", "1");
            para.Add("WorkflowStepID", strWorkflowStepID);
            para.Add("State", "0");

            //产品序号
            DataTable dtProductNo = common.GetProductNo(strContainerID);

            //加工人员
            DataTable dtEmployee = new DataTable();

            dispatch.AddDispatchInfo(para, dtProductNo, dtEmployee);

            startTime = endTime;
        }

        //给批次更新已预派工标记
        plat.UpdateContainerIsAPS(strContainerID);
    }
    #endregion

    #region 计划延迟处理
    /// <summary>
    /// 计划延迟处理
    /// </summary>
    /// <param name="intDays">天数：整数为延迟，负数为提前，绝对值为具体天数</param>
    /// <param name="dtSpecList">工序列表</param>
    /// <param name="dtDispatch">派工单列表</param>
    /// <param name="intRowIndex">批次行号</param>
    protected void DelayPlan(int intDays, DataTable dtSpecList, DataTable dtDispatch, int intRowIndex)
    {
        string strContainerID = ItemGrid.Rows[intRowIndex].Cells.FromKey("ContainerID").Value.ToString();
        string strWorkflowID = ItemGrid.Rows[intRowIndex].Cells.FromKey("WorkflowID").Value.ToString();
        string IsAPS = ItemGrid.Rows[intRowIndex].Cells.FromKey("IsAPS").Value.ToString();

        //更新批次的计划开始时间和计划完成时间
        string strPlannedStartDate = ItemGrid.Rows[intRowIndex].Cells.FromKey("PlannedStartDate").Value.ToString();
        DateTime startDate = Convert.ToDateTime(strPlannedStartDate);
        string strPlannedCompletionDate = ItemGrid.Rows[intRowIndex].Cells.FromKey("PlannedCompletionDate").Value.ToString();
        DateTime endDate = Convert.ToDateTime(strPlannedCompletionDate);

        startDate = startDate.AddDays(intDays);
        //endDate = endDate.AddDays(intDays);

        plat.UpdateContainerDate(strContainerID, startDate, endDate);

        //更新批次对应订单的计划开始时间和计划完成时间
        //plat.UpdateMfgOrderDate(strContainerID, intDays);

        MESAuditLog ml = new MESAuditLog();//日志记录对象 add:Wangjh
        ml.ContainerID = strContainerID;
        ml.ContainerName= ItemGrid.Rows[intRowIndex].Cells.FromKey("ContainerName").Text;

        if (IsAPS == "0") //默认为零，即批次尚未进行预派工操作
        {
            APS(dtSpecList, intRowIndex, startDate);
            ml.OperationType = 0;          
            ml.Description = "批次预派工:" + ml.ContainerName + "预派工成功";
        }
        else
        {
            string strSequence = ItemGrid.Rows[intRowIndex].Cells.FromKey("Sequence").Value.ToString();

            DataRow[] rows = dtDispatch.Select(string.Format("ContainerID = '{0}' AND WorkflowID = '{1}' AND SpecSequence >= {2}", strContainerID, strWorkflowID, strSequence));

            foreach (DataRow row in rows)
            {
                string strID = row["ID"].ToString();
                string strStartTime = row["PlannedStartDate"].ToString();
                string strEndTime = row["PlannedCompletionDate"].ToString();

                startDate = Convert.ToDateTime(strStartTime);
                endDate = Convert.ToDateTime(strEndTime);

                startDate = startDate.AddDays(intDays);
                endDate = endDate.AddDays(intDays);

                //更新派工单的计划开始时间和计划完成时间
                plat.UpdateDispatchInfo(strID, startDate, endDate);
            }
            ml.OperationType =1;
            ml.Description = "批次预派工:" + ml.ContainerName + "预派工修改成功";
        }
        ContainerExcuteLog(ml);
    }

    /// <summary>
    /// 计划延迟处理入口
    /// </summary>
    /// <param name="intDays">天数，正数为延迟，负数为提前</param>
    protected void Delay(int intDays)
    {
        int intCount = 0;
        List<string> listWorkflowID = new List<string>();
        List<string> listContainerID = new List<string>();

        TemplatedColumn temCell = (TemplatedColumn)ItemGrid.Columns.FromKey("ckSelect");

        for (int i = 0; i < temCell.CellItems.Count; i++)
        {
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell.CellItems[i];
            CheckBox ckSelect = (CheckBox)cellItem.FindControl("ckSelect");

            if (ckSelect.Checked == true)
            {
                string strWorkflowID = ItemGrid.Rows[i].Cells.FromKey("WorkflowID").Value.ToString();
                listWorkflowID.Add(strWorkflowID);
                string strContainerID = ItemGrid.Rows[i].Cells.FromKey("ContainerID").Value.ToString();
                listContainerID.Add(strContainerID);

                intCount++;
            }
        }

        if (intCount == 0)
        {
            ShowStatusMessage("请选择要延迟计划的批次", false);
            return;
        }

        //获取工序列表
        DataTable DT = common.GetSpecListByWorkflowID(listWorkflowID);

        //获取班组派工列表
        DataTable dtDispatch = plat.GetDispatchListByContainerID(listContainerID);

        for (int i = 0; i < temCell.CellItems.Count; i++)
        {
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell.CellItems[i];
            CheckBox ckSelect = (CheckBox)cellItem.FindControl("ckSelect");

            if (ckSelect.Checked == true)
            {
                DelayPlan(intDays, DT, dtDispatch, i);
            }
        }

        Dictionary<string,string> para = (Dictionary<string, string>)Session[QueryWhere];
        QueryData(para);

        ShowStatusMessage("预派工完成", true);
    }
    #endregion

    #region 计划延迟一天
    protected void Button1_Click(object sender, EventArgs e)
    {
        //ClearMessage();

        try
        {
            Delay(1);
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }
    #endregion

    #region 计划延迟一周
    protected void Button2_Click(object sender, EventArgs e)
    {
        //ClearMessage();

        try
        {
            Delay(7);
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }
    #endregion

    #region 计划延迟一月
    protected void Button3_Click(object sender, EventArgs e)
    {
        //ClearMessage();

        try
        {
            Delay(30);
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }
    #endregion

    protected void btnOK_Click(object sender, EventArgs e)
    {
        //ClearMessage();

        try
        {
            string strD = txtTS.Text.Trim();

            if (strD == string.Empty)
            {
                ShowStatusMessage("请输入天数", false);
                txtTS.Focus();
                return;
            }

            int intD = 0;
            try
            {
                intD = Convert.ToInt32(strD);
            }
            catch
            {
                ShowStatusMessage("天数必须是数字", false);
                txtTS.Focus();
                return;
            }

            if (strD.Contains("."))
            {
                ShowStatusMessage("天数必须是整数", false);
                txtTS.Focus();
                return;
            }

            if (intD <= 0)
            {
                ShowStatusMessage("天数必须是大于零", false);
                txtTS.Focus();
                return;
            }

            int TorY = Convert.ToInt32(ddlTY.SelectedValue);

            Delay(intD * TorY);

            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>parent.window.returnValue='true';window.close();</script>");
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    protected void ItemGrid_DataBound(object sender, EventArgs e)
    {
        for (int i = 0; i < ItemGrid.Rows.Count; i++)
        {
            string strIsAPS = ItemGrid.Rows[i].Cells.FromKey("IsAPS").Value.ToString();

            if (strIsAPS == "1") //已派工
            {
                ItemGrid.Rows[i].Cells.FromKey("IsAPSDisplay").Style.BackColor = Color.Red;
                ItemGrid.Rows[i].Cells.FromKey("IsAPSDisplay").Text = "已派工";
            }
            else
            {
                ItemGrid.Rows[i].Cells.FromKey("IsAPSDisplay").Style.BackColor = Color.Green;
                ItemGrid.Rows[i].Cells.FromKey("IsAPSDisplay").Text = "未派工";
            }
            string strState = ItemGrid.Rows[i].Cells.FromKey("State").Value.ToString();

            if (strState == "1") //已下发
            {
                ItemGrid.Rows[i].Cells.FromKey("State").Style.BackColor = Color.LightSeaGreen;
                ItemGrid.Rows[i].Cells.FromKey("State").Text = "";

                ItemGrid.Rows[i].Cells.FromKey("ckSelect").AllowEditing = AllowEditing.No;
            }
            else if (strState == "10") // 已审核通过
            {
                ItemGrid.Rows[i].Cells.FromKey("State").Style.BackColor = Color.LightGreen;
                ItemGrid.Rows[i].Cells.FromKey("State").Text = "";

                ItemGrid.Rows[i].Cells.FromKey("ckSelect").AllowEditing = AllowEditing.No;
            }
            else if (strState == "20") // 审核未通过
            {
                ItemGrid.Rows[i].Cells.FromKey("State").Style.BackColor = Color.LightYellow;
                ItemGrid.Rows[i].Cells.FromKey("State").Text = "";

                ItemGrid.Rows[i].Cells.FromKey("ckSelect").AllowEditing = AllowEditing.Yes;
            }
            else //未审核
            {
                ItemGrid.Rows[i].Cells.FromKey("State").Style.BackColor = Color.LightSkyBlue;
                ItemGrid.Rows[i].Cells.FromKey("State").Text = "";

                ItemGrid.Rows[i].Cells.FromKey("ckSelect").AllowEditing = AllowEditing.Yes;
            }
        }
    }

    protected void Button4_Click(object sender, EventArgs e)
    {
        try
        {
            //ClearMessage();

            UltraGridRow uldr = ItemGrid.DisplayLayout.ActiveRow;
            if (uldr == null)
            {
                ShowStatusMessage("请选择订单记录", false);
                //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>alert('请选择批次记录')</script>");
                return;
            }

            DataTable poupDt = new DataTable();
            poupDt.Columns.Add("ProductID");
            poupDt.Columns.Add("WorkflowID"); poupDt.Columns.Add("ContainerID"); poupDt.Columns.Add("ContainerName");
            DataRow newRow = poupDt.NewRow();
            newRow["ProductID"] = uldr.Cells.FromKey("ProductID").Text;
            newRow["WorkflowID"] = uldr.Cells.FromKey("Workflowid").Text;
            newRow["ContainerID"] = uldr.Cells.FromKey("ContainerID").Text;
            newRow["ContainerName"] = uldr.Cells.FromKey("ContainerName").Text;
            poupDt.Rows.Add(newRow);
            Session.Add("ProcessDocument", poupDt);
            string strScript = string.Empty;

            strScript = "<script>window.showModalDialog('Custom/bwCommonPage/uMESDocumentViewPopupForm.aspx', '', 'dialogWidth: 700px; dialogHeight: 600px; status = no; center: Yes; resizable: NO; ')</script>";
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }


    protected void btnSelectAll_Click(object sender, EventArgs e)
    {
        if (btnSelectAll.Text == "全选")
        {
            btnSelectAll.Text = "全不选";
            uMESCommonFunction.ResetGridCheckStatus2(ItemGrid, "ckSelect", 0);
        }
        else if (btnSelectAll.Text == "全不选")
        {
            btnSelectAll.Text = "全选";
            uMESCommonFunction.ResetGridCheckStatus2(ItemGrid, "ckSelect", 2);
        }

    }

    protected void btnInRevert_Click(object sender, EventArgs e)
    {
        uMESCommonFunction.ResetGridCheckStatus2(ItemGrid, "ckSelect", 1);
    }

    #region 提示信息
    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        //DisplayMessage(strMessage,boolResult);

        Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>alert('" + strMessage + "');</script>");

    }
    #endregion

    #region 树形区域 add:Wangjh 20201020


    /// <summary>
    /// 遍历所有子节点，并查询订单
    /// </summary>
    /// <param name="childNodes"></param>
    /// <param name="dt"></param>
    void GetChildNodesData2(Nodes childNodes, DataSet ds)
    {

        foreach (Node node in childNodes)
        {
            DataSet tempDs = QueryData3("",node.Text.ToString());

            ds.Tables[0].Merge(tempDs.Tables[0]);

            GetChildNodesData2(node.Nodes, ds);
        }
    }

    /// <summary>
    /// 查询该产品及其以下所有
    /// </summary>
    void SearchAllData2()
    {
        DisabledPage();
        ItemGrid.Rows.Clear();
        var selectNode = treeProduct.SelectedNode;
        if (selectNode == null)
        {
            ShowStatusMessage("请先选择节点", false);
            return;
        }
        // selectNode.nod
        DataSet ds = QueryData3("",selectNode.Text.ToString());

        GetChildNodesData2(selectNode.Nodes, ds);

        ItemGrid.DataSource = ds.Tables[0];
        ItemGrid.DataBind();
    }

    protected void btnSearchAll_Click(object sender, EventArgs e)
    {
        try { 
            SearchAllData2(); } catch (Exception ex) { ShowStatusMessage(ex.Message, false); }
    }

    public void QueryData2(string productID, string productName)
    {
        try
        {
            ItemGrid.Rows.Clear();

            // Dictionary<string, string> para = GetQuery();

            Dictionary<string, string> para = new Dictionary<string, string>();
            para["PageSize"] = m_PageSize.ToString();
            if (!string.IsNullOrWhiteSpace(productID))
                para["ProductID"] = productID;
            if (!string.IsNullOrWhiteSpace(productName))
                para["ProductName2"] = productName;
            if (!string.IsNullOrWhiteSpace(txtTreeProcessNo.Text))
            {
                para["ProcessNo"] = txtTreeProcessNo.Text;
            }

            string strStartDate = txtStartDate.Value.Trim();
            string strEndDate = txtEndDate.Value.Trim();
            if (!string.IsNullOrWhiteSpace(strStartDate))
            {
                para.Add("StartDate", strStartDate);
            }

            if (!string.IsNullOrWhiteSpace(strEndDate) )
            {
                para.Add("EndDate", strEndDate);
            }

            if (para.ContainsKey("StartDate") && para.ContainsKey("EndDate"))
            {
                DateTime dtStartDate = Convert.ToDateTime(strStartDate);
                DateTime dtEndDate = Convert.ToDateTime(strEndDate);

                if (dtStartDate > dtEndDate)
                {
                    ShowStatusMessage("截止日期应晚于开始日期", false);
                    return;
                }
            }                  
            
            para.Add("IsAPS", "0"); para.Add("State", "0,20");

            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            string strEmployeeID = userInfo["EmployeeID"];
            para.Add("MfgManagerid", strEmployeeID);

            uMESPagingDataDTO result = bll.GetSourceData(para, 1, 100000);

            ItemGrid.DataSource = result.DBTable;
            ItemGrid.DataBind();
        }
        catch (Exception e)
        {
            ShowStatusMessage(e.Message, false);
        }

    }

    public DataSet QueryData3(string productID, string productName)
    {
        try
        {
            // Dictionary<string, string> para = GetQuery();
            DataSet re = new DataSet();

            Dictionary<string, string> para = new Dictionary<string, string>();
            para["PageSize"] = m_PageSize.ToString();
            if (!string.IsNullOrWhiteSpace(productID))
                para["ProductID"] = productID;
            if (!string.IsNullOrWhiteSpace(productName))
                para["ProductName2"] = productName;

            if (!string.IsNullOrWhiteSpace(txtTreeProcessNo.Text))
            {
                para["ProcessNo"] = txtTreeProcessNo.Text;
            }

            string strStartDate = txtStartDate.Value.Trim();
            string strEndDate = txtEndDate.Value.Trim();
            if (!string.IsNullOrWhiteSpace(strStartDate))
            {
                para.Add("StartDate", strStartDate);
            }

            if (!string.IsNullOrWhiteSpace(strEndDate))
            {
                para.Add("EndDate", strEndDate);
            }

            if (para.ContainsKey("StartDate") && para.ContainsKey("EndDate"))
            {
                DateTime dtStartDate = Convert.ToDateTime(strStartDate);
                DateTime dtEndDate = Convert.ToDateTime(strEndDate);

                if (dtStartDate > dtEndDate)
                {
                    ShowStatusMessage("截止日期应晚于开始日期", false);
                    return re;
                }
            }

            para.Add("IsAPS", "0"); para.Add("State", "0,20");

            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            string strEmployeeID = userInfo["EmployeeID"];
            para.Add("MfgManagerid", strEmployeeID);


            uMESPagingDataDTO result = bll.GetSourceData(para, 1, 100000);
            re.Tables.Add(result.DBTable);

            return re;
        }
        catch (Exception e)
        {
            ShowStatusMessage(e.Message, false);
            return null;
        }

    }


    protected void treeProduct_NodeSelectionChanged(object sender, WebTreeNodeEventArgs e)
    {
        try
        {
            DisabledPage();
            // upageTurning.InitControl();
            ResetData();
            selectProductNode();

        }
        catch (Exception ex) { ShowStatusMessage(ex.Message, false); }

    }

    void selectProductNode()
    {
        // var selectNode = tvTree.SelectedNode;
        // string productID = selectNode.Value;

        var selectNode = treeProduct.SelectedNode;
        string productID = selectNode.Tag.ToString();

        txtSrTreeProduct.Text = selectNode.Text;
        txtSrTreeProcessNo.Text = txtTreeProcessNo.Text;
        QueryData2("",selectNode.Text);
    }


    protected void btnTreeSearch_Click(object sender, EventArgs e)
    {
        //ClearMessage();

        try {
            TreeSearchProduct();
            //ProductTreeSearch();
        } catch (Exception ex) { ShowStatusMessage(ex.Message, false); }

    }

    //获取产品名及版本
    void GetProductInfo(ref string productName, ref string productRev)
    {
        string productInfo = getProductInfo.ProducText;

        if (productInfo == "")
        {
            return;
        }

        productName = productInfo.Substring(0, productInfo.IndexOf(":"));
        productRev = productInfo.Substring(productInfo.IndexOf(":") + 1, productInfo.IndexOf("(", productName.Length) - productInfo.IndexOf(":") - 1);

    }

    //UltraWebTree
    Node GetProductTree2(string productName, string productRev, DataTable dt)
    {
        Node productTree = new Node();

        DataRow[] drs = dt.Select(string.Format("productname='{0}' and productrev='{1}'", productName, productRev));


        for (int i = 0; i < drs.Length; i++)
        {
            Node productSubTree = GetProductTree2(drs[i]["subproductname"].ToString(), drs[i]["subproductrev"].ToString(), dt);

            productSubTree.Text = drs[i]["subproductname"].ToString();// + ":" + drs[i]["subproductrev"].ToString(); //+ " | " + drs[i]["subproductstatus"].ToString();
            productSubTree.Tag = drs[i]["subproductid"].ToString();
            productTree.Nodes.Add(productSubTree);
            if (drs[i]["IsCommon"].ToString() == "1")
            {
                productSubTree.Styles.ForeColor = Color.Blue;
                productSubTree.ToolTip = "公共件";
            }
        }

        return productTree;

    }


    /// <summary>
    /// 产品结构树
    /// </summary>
    void ProductTreeSearch()
    {
        treeProduct.Nodes.Clear();

        string productName = "", productRev = "";
        GetProductInfo(ref productName, ref productRev);
        if (string.IsNullOrWhiteSpace(productName))
        {
            ShowStatusMessage("请选择产品", false);
            return;
        }
        if (string.IsNullOrWhiteSpace(txtTreeProcessNo.Text))
        {
            ShowStatusMessage("请选择工作令号", false);
            return;
        }
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("ProductName", productName); para.Add("ProductRev", productRev);
        para.Add("ProcessNo", txtTreeProcessNo.Text);//工作令号
        DataTable dt = productTreeBal.GetSubProductInfo(para);

        if (dt.Rows.Count == 0)
        {
            ShowStatusMessage("此产品没有子级零组件", false);
            return;
        }
        //TreeView
        /*
        TreeNode productTree = GetProductTree(productName, productRev, dt);
        DataRow[] drs = dt.Select(string.Format("productname='{0}' and productrev='{1}'", productName, productRev));
        productTree.Text = drs[0]["productname"].ToString() + ":" + drs[0]["productrev"].ToString(); //+ " | " + drs[0]["productStatus"].ToString();
        productTree.Value = drs[0]["productid"].ToString();
        tvTree.Nodes.Add(productTree);
        tvTree.Nodes[0].Expand();
        */
        //UltraWebTree
        Node productTree = GetProductTree2(productName, productRev, dt);
        DataRow[] drs = dt.Select(string.Format("productname='{0}' and productrev='{1}'", productName, productRev));
        productTree.Text = drs[0]["productname"].ToString();// + ":" + drs[0]["productrev"].ToString(); //+ " | " + drs[0]["productStatus"].ToString();
        productTree.Tag = drs[0]["productid"].ToString();
        treeProduct.Nodes.Add(productTree);
        treeProduct.Nodes[0].Expand(false);
    }

    protected void btnTreeReset_Click(object sender, EventArgs e)
    {
        try
        {
            ResetData();
            txtTreeProcessNo.Text = string.Empty;
            getProductInfo.InitControl();
            treeProduct.Nodes.Clear();
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    /// <summary>
    /// 根据工作令号查询产品
    /// </summary>
    void TreeSearchProduct()
    {
        treeProduct.Nodes.Clear();
        if (string.IsNullOrWhiteSpace(txtTreeProcessNo.Text))
        {
            ShowStatusMessage("请选择工作令号", false);
            return;
        }
        DataTable dt = containerBal.GetProductByProcess(txtTreeProcessNo.Text);
        getProductInfo.GetProductDDL.Visible = true;
        getProductInfo.GetProductNameOrTypeText.Visible = false;

        getProductInfo.GetProductDDL.DataTextField = "PRODUCTNAME";
        getProductInfo.GetProductDDL.DataValueField = "PRODUCTID";
        getProductInfo.GetProductDDL.DataSource = dt;
        getProductInfo.GetProductDDL.DataBind();

        getProductInfo.GetProductDDL.Items.Insert(0, "");
    }
    #endregion
    /// <summary>
    /// 禁用分页
    /// </summary>
    void DisabledPage() {
        lbtnFirst.Enabled = false;
        lbtnPrev.Enabled = false;
        lbtnNext.Enabled = false;
        lbtnLast.Enabled = false;
        lLabel1.Text = "第  页  共  页";
        txtPage.Text = "";
        btnGo.Enabled = false;

    }
    /// <summary>
    /// 启用分页
    /// </summary>
    void EnabledPage() {
        lbtnFirst.Enabled = true ;
        lbtnPrev.Enabled = true;
        lbtnNext.Enabled = true;
        lbtnLast.Enabled = true;
        btnGo.Enabled = true;
    }

    #region 批次日志记录 add:Wangjh 20210120
    void ContainerExcuteLog(Dictionary<string,string> para) {
        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        List<MESAuditLog> entitys = new List<MESAuditLog>();
        MESAuditLog ml = new MESAuditLog();
        foreach (string key in para.Keys) {
            ml = new MESAuditLog();
            ml.ContainerName = para[key]; ml.ContainerID =key;
            ml.ParentID = key; ml.ParentName = parentName;
            ml.CreateEmployeeID = userInfo["EmployeeID"];
            ml.BusinessName = businessName; ml.OperationType = 0;
            ml.Description = "批次预派工:" + ml.ContainerName + "预派工成功";

            entitys.Add(ml);

        }
        if(entitys.Count>0)
            common.SaveMESAuditLogs(entitys);
    }

    void ContainerExcuteLog(MESAuditLog ml)
    {
        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        ml.ParentName = parentName; ml.BusinessName = businessName;
        ml.CreateEmployeeID = userInfo["EmployeeID"];ml.ParentID = ml.ContainerID;
        common.SaveMESAuditLog(ml);
    }
    #endregion
}